<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>批次追踪表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="together-content">
      <!-- 搜索区域 -->
      <div class="search-form">
        <el-form :inline="true" :model="searchForm" size="small">
          <el-form-item label="单据日期">
            <el-date-picker
              v-model="searchForm.startDate"
              type="date"
              placeholder="开始日期"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 120px"
            />
            <span style="margin: 0 5px">至</span>
            <el-date-picker
              v-model="searchForm.endDate"
              type="date"
              placeholder="结束日期"
              value-format="YYYY-MM-DD"
              clearable
              style="width: 120px"
            />
          </el-form-item>

          <el-form-item label="仓库">
            <el-input
              v-model="input"
              readonly
              placeholder="选择仓库"
              @click="warehouseVisible = true"
              style="width: 180px"
            />
          </el-form-item>

          <el-form-item label="商品">
            <el-select
              v-model="searchForm.productName"
              placeholder="请选择商品"
              clearable
              filterable
              style="width: 150px"
            >
              <el-option
                v-for="name in uniqueProductNames"
                :key="name"
                :label="name"
                :value="name"
              />
            </el-select>
          </el-form-item><br/>

          <el-form-item label="业务类型">
            <el-select
              v-model="searchForm.businessType"
              placeholder="请选择业务类型"
              clearable
              style="width: 130px"
            >
              <el-option label="普通采购" value="普通采购" />
              <el-option label="退货" value="退货" />
              <el-option label="销售" value="销售" />
              <el-option label="其他入库" value="其他入库" />
              <el-option label="成本调整" value="成本调整" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 分割线 -->
        <el-divider style="margin: 10px 0" />
      </div>
      <!-- 仓库搜索列表弹出对话框 -->
      <el-dialog
        v-model="warehouseVisible"
        title="仓库搜索列表"
        width="40%"
        style="height: auto;"
        draggable
        :show-close="true">
        <!-- 调用仓库的搜索组件 -->
        <WareHouse ref="warehouseRef" :info="{selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true}"/>
        <br/><br/>
      </el-dialog>

      <!-- 导出和打印按钮 -->
      <div class="table-header-buttons">
        <el-button type="primary" size="small" @click="handleExport"
          >导出</el-button
        >
        <el-button size="small" @click="handlePrint">打印</el-button>
      </div>
      <br />
      <!-- 表格容器 -->
      <el-table
        :data="displayData"
        border
        stripe
        :header-cell-style="{ background: '#f5f7fa', fontWeight: 'bold' }"
        style="width: 100%"
        :max-height="600"
        v-loading="loading"
        show-summary
        sum-text="总计"
      >
        <el-table-column
          prop="productCode"
          label="商品编号"
          width="100"
          align="center"
        />
        <el-table-column
          prop="productName"
          label="商品名称"
          width="150"
          align="center"
        />
        <el-table-column
          prop="unitPrice"
          label="单价"
          width="80"
          align="center"
        >
          <template #default="{ row }">
            {{ Number(row.unitPrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="taxPrice"
          label="含税单价"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ Number(row.taxPrice).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="100" align="center">
          <template #default="{ row }">
            {{ Number(row.amount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="taxAmount"
          label="税额"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ Number(row.taxAmount).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="totalTax"
          label="价税合计"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            {{ Number(row.totalTax).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="origin"
          label="产地"
          width="100"
          align="center"
        />
        <el-table-column
          prop="registrationNo"
          label="注册证号"
          width="120"
          align="center"
        />
        <el-table-column
          prop="productionLicense"
          label="生产许可证"
          width="120"
          align="center"
        />
        <el-table-column
          prop="specification"
          label="规格型号"
          width="120"
          align="center"
        />
        <el-table-column prop="brand" label="品牌" width="100" align="center" />
        <el-table-column prop="unit" label="单位" width="80" align="center" />
        <el-table-column
          prop="subUnit"
          label="副单位"
          width="80"
          align="center"
        />
        <el-table-column
          prop="warehouse"
          label="仓库"
          width="100"
          align="center"
        />
        <el-table-column prop="batch" label="批次" width="120" align="center" />
        <el-table-column
          prop="productionDate"
          label="生产日期"
          width="120"
          align="center"
        />
        <el-table-column
          prop="shelfLifeDays"
          label="保质期天数"
          width="120"
          align="center"
        />
        <el-table-column
          prop="expiryDate"
          label="有效期至"
          width="120"
          align="center"
        />
        <el-table-column
          prop="quantity"
          label="数量"
          width="80"
          align="center"
        />
        <el-table-column
          prop="subQuantity"
          label="副单位数"
          width="100"
          align="center"
        />
        <el-table-column
          prop="orderCode"
          label="单据编号"
          width="150"
          align="center"
        />
        <el-table-column
          prop="orderDate"
          label="单据日期"
          width="120"
          align="center"
        />
        <el-table-column
          prop="businessType"
          label="业务类型"
          width="120"
          align="center"
        />
        <el-table-column
          prop="clientSupplier"
          label="客户/供应商"
          width="150"
          align="center"
        />
        <el-table-column
          prop="salesPerson"
          label="销售人员"
          width="120"
          align="center"
        />
        <el-table-column
          prop="remark"
          label="备注"
          width="120"
          align="center"
        />
        <el-table-column
          prop="wholeRemark"
          label="整单备注"
          width="150"
          align="center"
        />
      </el-table><br/>

      <!-- 分页 -->
      <div class="page-div">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="10"
          layout="total, ->, prev, pager, next, jumper"
          background
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ArrowRight } from "@element-plus/icons-vue";
import WareHouse from "@/views/basic/WareHouse.vue";
//仓库搜索选中结果
let warehouseVisible = ref(false);
let input = ref("");
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
  if (!newVisible) {
    if (warehouseRef.value) {
      //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
      input.value = warehouseRef.value.selectedArray
        .map((item) => item.name)
        .join(",");
      //获取到仓库编码，存数据库用，仓库name仅用作展示
      //用完之后清空，避免污染其他地方数据
      warehouseRef.value.clearSelected();
    }
  }
});
// 模拟数据：批次追踪表
const rawData = ref([
  {
    productCode: "572",
    productName: "测试瓷砖",
    unitPrice: 8.85,
    taxPrice: 10.0,
    amount: 884.96,
    taxAmount: 115.04,
    totalTax: 1000.0,
    origin: "",
    registrationNo: "",
    productionLicense: "",
    specification: "白色",
    brand: "",
    unit: "块",
    subUnit: "",
    warehouse: "默认仓库",
    batch: "20251023001",
    productionDate: "2025-10-23",
    shelfLifeDays: 9999,
    expiryDate: "2053-03-09",
    quantity: 100,
    subQuantity: 0,
    orderCode: "GH20251023016",
    orderDate: "2025-10-23",
    businessType: "普通采购",
    clientSupplier: "1000021WWZZ",
    salesPerson: "",
    remark: "",
    wholeRemark: "",
  },
  {
    productCode: "572",
    productName: "测试瓷砖",
    unitPrice: 8.85,
    taxPrice: 10.0,
    amount: 530.97,
    taxAmount: 69.03,
    totalTax: 600.0,
    origin: "",
    registrationNo: "",
    productionLicense: "",
    specification: "白色",
    brand: "",
    unit: "块",
    subUnit: "",
    warehouse: "冷配库",
    batch: "20251023001",
    productionDate: "2025-10-23",
    shelfLifeDays: 9999,
    expiryDate: "2053-03-09",
    quantity: 60,
    subQuantity: 0,
    orderCode: "GH20251023016",
    orderDate: "2025-10-23",
    businessType: "普通采购",
    clientSupplier: "1000021WWZZ",
    salesPerson: "",
    remark: "",
    wholeRemark: "",
  },
  {
    productCode: "572",
    productName: "测试瓷砖",
    unitPrice: 13.27,
    taxPrice: 15.0,
    amount: 530.97,
    taxAmount: 69.03,
    totalTax: 600.0,
    origin: "",
    registrationNo: "",
    productionLicense: "",
    specification: "白色",
    brand: "",
    unit: "块",
    subUnit: "",
    warehouse: "冷配库",
    batch: "20251022",
    productionDate: "2025-10-23",
    shelfLifeDays: 9999,
    expiryDate: "2053-03-09",
    quantity: 40,
    subQuantity: 0,
    orderCode: "GH20251023016",
    orderDate: "2025-10-23",
    businessType: "普通采购",
    clientSupplier: "1000021WWZZ",
    salesPerson: "",
    remark: "",
    wholeRemark: "",
  },
  {
    productCode: "SP0224",
    productName: "88888",
    unitPrice: 0.0,
    taxPrice: 0.0,
    amount: 0.0,
    taxAmount: 0.0,
    totalTax: 0.0,
    origin: "",
    registrationNo: "",
    productionLicense: "",
    specification: "",
    brand: "",
    unit: "袋",
    subUnit: "",
    warehouse: "食品库",
    batch: "20251023",
    productionDate: "2025-10-23",
    shelfLifeDays: 90,
    expiryDate: "2026-01-21",
    quantity: 100,
    subQuantity: 0,
    orderCode: "GH20251023006",
    orderDate: "2025-10-23",
    businessType: "普通采购",
    clientSupplier: "G00001青岛坤合批发有限公司",
    salesPerson: "",
    remark: "",
    wholeRemark: "",
  },
]);

// 搜索表单
const searchForm = reactive({
  startDate: "",
  endDate: "",
  warehouse: "",
  productName: "",
  businessType: "",
});

// 计算唯一选项
// const uniqueWarehouses = computed(() => [
//   ...new Set(rawData.value.map((i) => i.warehouse)),
// ]);
const uniqueProductNames = computed(() => [
  ...new Set(rawData.value.map((i) => i.productName)),
]);

// 过滤后的数据显示
const displayData = computed(() => {
  return rawData.value.filter((item) => {
    const matchesDate =
      (!searchForm.startDate || item.orderDate >= searchForm.startDate) &&
      (!searchForm.endDate || item.orderDate <= searchForm.endDate);
    const matchesWarehouse =
      !searchForm.warehouse || item.warehouse === searchForm.warehouse;
    const matchesName =
      !searchForm.productName || item.productName === searchForm.productName;
    const matchesBusinessType =
      !searchForm.businessType || item.businessType === searchForm.businessType;

    return (
      matchesDate && matchesWarehouse && matchesName && matchesBusinessType
    );
  });
});

// 加载状态
const loading = ref(false);

// 查询与重置
const handleQuery = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 500);
};

const resetSearch = () => {
  searchForm.startDate = "";
  searchForm.endDate = "";
  searchForm.warehouse = "";
  searchForm.productName = "";
  searchForm.businessType = "";
};

// 导出功能
const handleExport = () => {
  alert("导出功能已触发，可在此实现 Excel 导出逻辑");
};

// 打印功能
const handlePrint = () => {
  window.print();
};
</script>

<style scoped>
.table-header-buttons {
  margin-top: 10px;
  text-align: right;
}

::v-deep(.el-table tbody tr:hover > td) {
  background-color: #edd4587d !important;
  border-bottom-color: #c78e39;
}

::v-deep(.el-table .el-table__body td) {
  padding: 8px 0;
  height: 55px;
}

::v-deep(.el-table .el-table__header th) {
  padding: 10px 0;
  height: 44px;
  background-color: #f5f7fa;
}

::v-deep(.el-table__footer) {
  background-color: #d6d847bc !important;
  font-weight: bold;
  font-size: 14px;
}

</style>